/*
 * @Author: Klein
 * @Date: 2021-06-17 14:08:18
 * @Description: file content
 */

const bcrypt = require("../lib/bcrypt");
const Message = require("../lib/message");
const UserDao = require("../dao/user");

const { tokenGet } = require("../lib/token");

class UserController {
  /**
   * @description: 校验登录账号跟登录密码是否没有填写
   * @description: 校验账号是否注册
   */
  static async validate(ctx, next) {
    const { name = "", password = "" } = ctx.request.body;
    if (!name) return (ctx.body = Message.error(400, "请输入登录账号"));
    if (!password) return (ctx.body = Message.error(400, "请输入登录密码"));
    const res = await UserDao.findUser(name);
    if (res) return (ctx.body = Message.error(401, "该账号已注册"));
    await next();
  }

  /**
   * @description: 登录密码进行加密
   */
  static async pswBcrypt(ctx, next) {
    const { password } = ctx.request.body;
    const _psw = bcrypt.hash(password);
    ctx.request.body.password = _psw;
    await next();
  }

  static async complete(ctx) {
    await UserDao.createUser(ctx.request.body);
    ctx.body = Message.success({ message: "注册成功" });
  }

  static async login(ctx) {
    const { name = "", password = "" } = ctx.request.body;
    const result = await UserDao.findUser(name);
    if (!result) return (ctx.body = Message.error(401, "该账号没有注册"));
    const isVerify = bcrypt.compare(password, result.password);
    if (!isVerify) return (ctx.body = Message.error(402, "登录密码错误"));
    const token = tokenGet(result.toJSON());
    ctx.body = Message.success({ ...result.toJSON(), token });
  }

  static async view(ctx) {
    const { name = "" } = ctx.state.jwtdata;
    const result = await UserDao.findUser(name);
    ctx.body = Message.success(result);
  }
}

module.exports = UserController;
